<template>
  <div class="list-page">
    <Row>
      <div class="toolbar">
        <Modal
          title="编辑规则"
          v-model="addrule"
          class-name="vertical-center-modal"
          @on-cancel="cancel"
          :width="600"
        >
          <p slot="header">
            <span>编辑规则</span>
          </p>
          <div style="text-align: center">
            <Form
              ref="editSort"
              :model="rule"
              :rules="ruleValidate"
              label-position="right"
              :label-width="100"
            >
              <FormItem label="设备分类:" prop="deviceSortId" required>
                <Select disabled v-model="rule.deviceSortId" @on-change="handleChange(rule.deviceSortId)" placeholder="设备分类"
                        style="width: 350px;margin-right: 10px">
                  <Option
                    v-for="item in bloc.sortList"
                    :value="item.id"
                    :key="item.id"
                  >{{ item.sortName }}
                  </Option>
                </Select>
              </FormItem>
              <FormItem label="设备型号:" prop="id" required>
                <Select disabled v-model="rule.id" placeholder="设备型号"
                        style="width:350px;margin-right:10px">
                  <Option
                    v-for="item in bloc.modelList"
                    :value="item.id"
                    :key="item.id"
                  >{{ item.modelName }}
                  </Option>
                </Select>
              </FormItem>
              <FormItem label="保养条件:" prop="usageTime" required>
                <div style="float: left;display: inline-block">
                  每使用 <Input v-model="rule.usageTime" :maxlength="5" style = 'width: 30%'/> 小时
<!--                  ， 或者每隔 <Input v-model="rule.serviceLife" :maxlength="5" style = 'width: 15%' /> 年-->
                </div>
              </FormItem>
<!--              <FormItem label="保养说明:" prop="description" required>-->
<!--                <Input-->
<!--                  type="textarea"-->
<!--                  :rows="4"-->
<!--                  v-model="rule.description"-->
<!--                  maxlength="500"-->
<!--                  show-word-limit-->
<!--                  placeholder="请输入保养（500字以内）"-->
<!--                  style="width: 400px"-->
<!--                />-->
<!--              </FormItem>-->
            </Form>
          </div>
          <div slot="footer">
            <AppButton
              ref="cancel"
              type="primary"
              @click="cancel"
            >取消</AppButton
            >
            <AppButton
              ref="save"
              type="primary"
              @click="editSorts('editSort')"
            >确定</AppButton
            >
          </div>
        </Modal>

        <Select v-model="bloc.model.sortId" @on-change="handleChange(bloc.model.sortId)" placeholder="设备分类"
                style="width: 180px;margin-right: 10px">
          <Option
            v-for="item in bloc.sortList"
            :value="item.id"
            :key="item.id"
          >{{ item.sortName }}
          </Option>
        </Select>
        <Select v-model="bloc.model.modelId" placeholder="设备型号" style="width:180px;margin-right:10px">
          <Option
            v-for="item in bloc.modelList"
            :value="item.id"
            :key="item.id"
          >{{ item.modelName }}
          </Option>
        </Select>

        <Button
          type="primary"
          icon="ios-search"
          style="margin: 0 10px"
          size="default"
          @click="bloc.load(1, bloc.paged.pageSize)"
        >查询
        </Button>
        <Button
          icon="md-refresh"
          style="margin-right: 10px"
          size="default"
          @click="bloc.reset()"
        >重置</Button
        >
      </div>
    </Row>
    <Row>
      <Table
        border
        :loading="bloc.loading"
        :columns="columns4"
        highlight-row
        :data="bloc.paged.items"
      >
        <template slot-scope="{ row }" slot="action">
          <div style="white-space: nowrap">
            <Button
              size="small"
              @click="handleAdd(row)"
             
              type="info"
            >编辑
            </Button>
<!--            <Button-->
<!--              size="small"-->
<!--              @click="removeItem(row)"-->
<!--              v-if="-->
<!--                            Validation.check(Resources.BANNERS_DELETE)-->
<!--                          "-->
<!--              type="warning"-->
<!--            >删除-->
<!--            </Button>-->

          </div>
        </template>
        <slot name="footer" slot="footer">
          <Page
            show-elevator
            show-total
            show-sizer
            :total="bloc.paged.itemCount"
            :current="bloc.paged.pageIndex"
            :page-size="bloc.paged.pageSize"
            :page-size-opts="[15, 30, 50, 100]"
            @on-change="(val) => bloc.load(val, bloc.paged.pageSize)"
            @on-page-size-change="(val) => bloc.load(bloc.paged.pageIndex, val)"
          />
        </slot>
      </Table>
    </Row>
  </div>

</template>

<script lang="ts">
    import {Component, Vue} from 'vue-property-decorator';
    import { Route } from 'vue-router';
    import { FormBloc } from '@/view/service/maintainregulation/FormBloc';
    import { formatDate } from '@/base/util/Dates';
    import { Validation } from '@/base/Validation';
    import { Resources } from '@/base/Resources';
    import { AppButton } from '@/type/AppButton';
    import CompanySeletorSingle from '@/component/CompanySeletorSingle.vue';
    import { isEmpty } from '@/base/util/Strings';

    @Component({
        components: {CompanySeletorSingle}
    })
    export default class extends Vue {

        columns4: any = [
        {
            title: '设备分类',
            key: 'sortId',
            render: (h: any, params: any) => {
                return h('span', {
                    domProps: {
                        innerText:
                            this.bloc.getsortName(params.row.sortId)
                    }
                });
            },
            align: 'left',
            minWidth: 200,
            tooltip: true
        },
        {
            title: '设备型号',
            key: 'modelName',
            align: 'left',
            minWidth: 100,
            tooltip: true
        },
        {
            title: '保养条件',
            key: 'usageTime',
            render: (h: any, params: any) => {
                return h('span', {
                    domProps: {
                        innerText: '每使用' + params.row.usageTime + '小时'
                        // + ",或者每隔"+params.row.serviceLife+"年"

                    }
                });
            },
            align: 'left',
            minWidth: 200,
            tooltip: true
        },
        {
            title: '修改时间',
            render: (h: any, params: any) => {
                return h('span', {
                    domProps: {
                        innerText: formatDate(
                            new Date(params.row.updated),
                            'yyyy-MM-dd hh:mm'
                        )
                    }
                });
            },
            width: 160,
            align: 'left',
            tooltip: true
        },

        {
            title: '操作',
            slot: 'action',
            width: 200,
            align: 'left',
            fixed: 'right'
        }
    ];
        beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
            next((vm) => {
                vm.bloc
                    .getAllSort(1, 1000, 'DESC').catch((e) => {
                    vm.$Message.error('分类错误');
                });
                vm.bloc.getAllModel(1, 1000, undefined, 'DESC', undefined).catch((e) => {
                    vm.$Message.error('模式错误');
                });
                vm.bloc.load(vm.bloc.paged.pageIndex, vm.bloc.paged.pageSize)
                    .catch((e) => {
                        vm.$Message.error('加载错误');
                    });
            });
        }
        bloc: FormBloc = new FormBloc();
        Validation = Validation;
        Resources = Resources;
        validateId3 = (rule: any, value: string, callback: any) => {
            isEmpty(this.rule.usageTime) || this.rule.usageTime === '0'
                ? callback(new Error('小时数不能为空且不能为0')) : /^[0-9]+$/.test(this.rule.usageTime) ? callback() : callback(new Error('小时数必须为数字'));
            // isEmpty(this.rule.year) || this.rule.year === 0
            //     ? callback(new Error('年不能为空')) : callback();
        };

        ruleValidate = {
            // deviceModelId: [
            //     {validator: this.validateId1, trigger: 'blur'}
            // ],
            // deviceSortId: [
            //     {validator: this.validateId2, trigger: 'blur'}
            // ],
            // deviceModelId: [
            //     {required: true, message: '设备分类不能为空', trigger: 'blur'}
            // ],
            // deviceSortId: [
            //     {required: true, message: '设备型号不能为空', trigger: 'blur'}
            // ],
            usageTime: [
                {validator: this.validateId3, trigger: 'blur'}
            ]
            // description: [
            //     {required: true, message: '保养说明不能为空', trigger: 'blur'}
            // ]
        };
        edit: any = false;
        addrule: any = false;
        rule: any = {
            deviceSortId: 0,
            id: 0,
            usageTime: 0,
            serviceLife: 0,
            description: ''
        };
        cancel() {
            if (this.$refs['addrule'] !== undefined) {
              this.$refs['addrule'].resetFields();
            }
            this.addrule = false;
           if (this.$refs['editSort'] !== undefined) {
              this.$refs['editSort'].resetFields();
           }
        }
        $refs!: {
            addrule: HTMLFormElement;
            editSort: HTMLFormElement;
            save: AppButton;
            cancel:AppButton;
            edit: AppButton;
        };

        handleAdd(item) {
            this.addrule = true;
            this.rule.deviceSortId = item.sortId;
            this.rule.id = this.bloc.getmodelId(item.modelName);
            this.rule.usageTime = item.usageTime;
            this.rule.serviceLife = item.serviceLife;
            this.rule.description = item.description;
        }

        handleChange(sortId) {
            this.bloc
                .getAllModel(1, 1000, sortId, 'DESC', undefined).then((res) => {});
        }

        private row: any;
        // removeItem(row) {
        //     this.row = row;
        //     this.$Modal.confirm({
        //         title: "提示",
        //         content: "确认删除后将无法恢复！还要继续吗？",
        //         okText: "删除",
        //         cancelText: "取消",
        //         onOk: () => {
        //             this.bloc.removeItem(row)
        //                 .then((res) => {
        //                     if (res.name === '') {
        //                         this.$Message.success('删除成功');
        //                     } else {
        //                         this.$Message.error('删除失败');
        //                     }
        //                 }).finally(() => {
        //                 this.bloc.reset();
        //             });
        //         },
        //     });
        // }

        editSorts(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.bloc.modifyItem(this.rule.deviceSortId, this.rule.id, this.rule.usageTime, this.rule.description)
                        .then((res) => {
                            this.edit = false;
                            this.$Message.success('编辑规则成功');
                            this.initTreeList();
                        })
                        .catch((res) => {
                            setTimeout(() => {
                                this.$Message.error('编辑规则失败');
                            }, 1500);
                        })
                        .finally(() => {
                            this.cancel();
                        });
                }
            });
        }
        initTreeList() {
            this.bloc.load(this.bloc.paged.pageIndex, this.bloc.paged.pageSize)
                .then((res) => {
                    // this.changeRoute();
                    this.bloc.getAllSort(1, 1000, 'ASC');
                    this.bloc.getAllModel(1, 1000, undefined, 'DESC', undefined);
                })
                .finally(() => {});
        }

        // changeRoute() {
        //     this.$router.push({
        //         path: '/service/nav/maitainregulation'
        //     });
        // }

    }

</script>

<style lang="less">
  .ivu-form-item-error-tip {
    left: 215px;
    top:3px;
  }
</style>
